<?php

namespace App\Http\Controllers\Api;

use App\AgentList;
use App\AgentOrder;
use App\Banner;
use App\Button;
use App\Classify;
use App\Course;
use App\CourseContent;
use App\CourseLabel;
use App\CoursePackage;
use App\CoursePackageXCourse;
use App\CourseType;

use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\DomainManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;

use App\IntegralDetail;
use App\OrderItem;
use App\OrderRefund;
use App\Orders;
use App\SystemGroup;
use App\SystemGroupXCourse;
use App\Teacher;
use App\User;
use App\UserCoupon;
use App\UserGroup;
use App\UserGroupXUser;
use App\UserInfo;
use App\VipInfo;
use DB;
use Exception;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;


class MallController extends Controller
{
    /**@author cmj
     * 获取首页banner轮播图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndexBannerList(Request $request){
        $banners=Banner::getIndexBanner();
        return response()->json(['level'=>'success','message'=>'success','data'=>$banners]);
    }

    /**@author cmj
     * 获取功能区按钮列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndexButtonList(Request $request){
        $button=Button::getIndexFunctionButton();
        return response()->json(['level'=>'success','message'=>'success','data'=>$button]);
    }

    public function getClassifyList(Request $request){
        $classify_id=$request->input('classify_id',0);
//        if (is_int($classify_id)){
//            $data=Classify::getClassifyInfo($classify_id);
//        } else {
            $data=Classify::getCourseClassifyList();
//        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$data]);
    }

    public function buildOrder(Request $request){

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $remark             = $request->input('remark','');
        $coupon_id          = $request->input('coupon_id',0);
        $sys_group_id       = $request->input('sys_group_id',0);
        $group_action       = $request->input('group_action','join');
        $join_group_id      = $request->input('join_group_id',0);
        $group_course_id    = $request->input('group_course_id',0);
        $packages_id        = $request->input('packages_id',0);
        $course_id_arr      = $request->input('course_id_arr',[]);
        $course_id          = $request->input('course_id',0);
        $vipType            = $request->input('vip_type','');
        $inviteUserId       = $request->input('invite_user_id',0);
        $isIntegralExchange = $request->input('is_integral_exchange',0);
        $province           = $request->input('province') ?? '';
        $city               = $request->input('city') ?? '';
        $area               = $request->input('area') ?? '';
        $phone              = $request->input('phone') ?? '';
        $realname           = $request->input('realname') ?? '';
        $sex                = $request->input('sex') ?? '';


//        $userInfo = UserInfo::whereUserId($user->id)->first();
//        if(!$userInfo)
//            return  response()->json(['level' => 'error','message' => '用户信息不存在']);
//
//        if(empty($user->phone) || empty($userInfo->realname) || empty($userInfo->company_name))
//            return response()->json(['level' => 'error','message' => '请完善个人信息','data' => 'no_User_info']);

        /** 创建单号 */
        $orderNum = ToolsManager::makeBillNum();
        while(true){
            $isOrders = Orders::whereOrderNum($orderNum)->first();
            if($isOrders){
                $orderNum = ToolsManager::makeBillNum();
            }else{
                break;
            }
        }
        if (is_string($group_action)){
            if (!in_array($group_action,['join','create']))
                return response()->json(['level'=>'error','message'=>'请选择参与拼团的方式']);
            if (!$group_course_id)
                return response()->json(['level'=>'error','message'=>'请选择参与拼团的课程']);
        }

        if(!$province || !$city || !$area)
            return response()->json(['level' => 'error','message' => '请选择所在地区']);

        if(!$phone)
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if($vipType != '' && in_array($vipType,['num','time'])){
            if($vipType == 'num'){
                $vipInfo = VipInfo::whereUserId($user->id)->whereType('num')->whereColumn('num','>','use_num')->first();
                if(!$vipInfo)
                    return response()->json(['level' => 'error','message' => '会员次数已用尽']);
            }elseif($vipType == 'time'){
                $vipInfo = VipInfo::whereUserId($user->id)->whereType('time')->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                if(!$vipInfo)
                    return response()->json(['level' => 'error','message' => '会员已过期']);
            }
        }

        try {
           DB::beginTransaction();
           /** 处理课程 */
           $thisOrder   = new Orders();
           $thisOrder->order_num= $orderNum;
           $thisOrder->user_id  = $user->id;
           $thisOrder->remark   = $remark ? $remark : '';
           $thisOrder->province = $province;
           $thisOrder->city     = $city;
           $thisOrder->area     = $area;
           $thisOrder->phone    = $phone;
           $thisOrder->sex      = $sex;
           $thisOrder->realname = $realname;
           $thisOrder->save();
           $total_original_price=0;
           $total_pay_amount    =0;
           $total_pay_integral  =0;
           $total_vip_num       =0;
           if ($packages_id){
               if (!is_array($course_id_arr)){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'套餐课程参数错误']);
               }
               if (count($course_id_arr) == 0){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'没有选择课程']);
               }

               //套餐下单
               $thisPackage=CoursePackage::whereId($packages_id)->first();
               if (!$thisPackage){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'套餐不存在']);
               }
                   $start_time  = (int)($thisPackage->start_time ? strtotime($thisPackage->start_time) : 0);
                   $end_time    = (int)($thisPackage->end_time   ? strtotime($thisPackage->end_time)   : 0);
                   if ($start_time > 0 && $start_time > time()){
                       DB::rollBack();
                       return response()->json(['level'=>'error','message'=>'套餐活动还未到开始时间']);
                   }
                   if ($end_time > 0 && $end_time < time()){
                       DB::rollBack();
                       return response()->json(['level'=>'error','message'=>'套餐活动已结束']);
                   }
                   $thisOrder->package_id   = $packages_id;
                   foreach ($course_id_arr as $course_id){
                       $thisCourse=Course::whereId($course_id)->lockForUpdate()->first();
                       if (!$thisCourse){
                           DB::rollBack();
                           return response()->json(['level'=>'error','message'=>'此课程不存在']);
                       }
                       if ($thisCourse->status!=1){
                           DB::rollBack();
                           return response()->json(['level'=>'error','message'=>"课程 $thisCourse->name 暂时不可购买"]);
                       }
                       /** @var CoursePackageXCourse $thisPackageCourse */
                       $thisPackageCourse=CoursePackageXCourse::whereCoursePackageId($thisPackage->id)
                           ->whereCourseId($course_id)->lockForUpdate()->first();
                       if (!$thisPackageCourse){
                           DB::rollBack();
                           return response()->json(['level'=>'error','message'=>"套餐内无 $thisCourse->name 课程"]);
                       }
                       if ($thisPackageCourse->remain_num <= 0){
                           DB::rollBack();
                           return response()->json(['level'=>'error','message'=>"来晚了啦，套餐内的 $thisCourse->name 已经被其他人抢完了"]);
                       }
                       $thisPackageCourse->remain_num   = $thisPackageCourse->remain_num-1;
                       $thisPackageCourse->sold_num     = $thisPackageCourse->sold_num  +1;
                       $thisPackageCourse->save();

                       $thisCourse->selling_num     =$thisCourse->selling_num + 1;
                       $thisCourse->save();
                       $total_original_price = $total_original_price + $thisCourse->price;
                       $orderItem                   = new OrderItem();
                       $orderItem->order_id         = $thisOrder->id;
                       $orderItem->user_id          = $user->id;
                       $orderItem->item_num         = $thisOrder->order_num.'#'.rand(1000,9999);
                       $orderItem->course_id        = $thisCourse->id;
                       $orderItem->original_price   = $thisCourse->price;
                       $orderItem->discount_price   = $thisPackageCourse->discount_price;
                       $orderItem->num              = 1;
                       $orderItem->total_amount     = round($orderItem->discount_price *  $orderItem->num ,2);
                       $orderItem->save();
                       $total_pay_amount            = $total_pay_amount + $orderItem->total_amount;
                   }

           } elseif ($sys_group_id && $group_action && $group_course_id){
               //拼团下单
//               $thisOrder->group_id=$sys_group_id;
               $thisGroup=SystemGroup::whereId($sys_group_id)->first();
               if (!$thisGroup){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'拼团活动不存在']);
               }
               $thisCourse=Course::whereId($group_course_id)->lockForUpdate()->first();
               if (!$thisCourse){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'此课程不存在']);
               }
               if ($thisCourse->status!=1){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>"课程 $thisCourse->name 暂时不可购买"]);
               }
               $thisGroupCourse=SystemGroupXCourse::whereSystemGroupsId($thisGroup->id)
                   ->whereCourseId($group_course_id)->first();
               if (!$thisGroupCourse){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>"活动内无 $thisCourse->name 课程"]);
               }
               if ($group_action=='create'){
                   $start_time  = (int)($thisGroup->start_time ? strtotime($thisGroup->start_time) : 0);
                   $end_time    = (int)($thisGroup->end_time   ? strtotime($thisGroup->end_time)   : 0);
                   if ($start_time > 0 && $start_time > time()){
                       DB::rollBack();
                       return response()->json(['level'=>'error','message'=>'拼团活动还未到开始时间']);
                   }
                   if ($end_time > 0 && $end_time < time()){
                       DB::rollBack();
                       return response()->json(['level'=>'error','message'=>'拼团活动已结束']);
                   }
                   //创建用户拼团
                   $userGroup                       = new UserGroup();
                   $userGroup->user_id              = $user->id;
                   $userGroup->system_groups_id     = $thisGroup->id;
                   $userGroup->course_id            = $group_course_id;
                   $userGroup->join_num             = 0;
                   $userGroup->status               = 0;
                   $userGroup->save();
                   $join_group_id                   =$userGroup->id;
               }
               //用户加入团
               if ($join_group_id==0){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'参团错误']);
               }

               /** @var UserGroup $thisUserGroup */
               $thisUserGroup=UserGroup::whereId($join_group_id)->lockForUpdate()->first();
               if (!$thisUserGroup){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'参与的团不存在']);
               }
               if ($thisGroup->require_num > 0 && $thisUserGroup->join_num >= $thisGroup->require_num){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'参与的团人数已满']);
               }
               $alreadyJoin=UserGroupXUser::whereUserId($user->id)->whereUserGroupId($join_group_id)->count();
               if ($alreadyJoin > 0){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'不能重复参团']);
               }
               $exp_time=(int)strtotime($thisUserGroup->created_at) + ($thisGroup->time_limit * 3600);
               if ($exp_time < time()){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'该团超过规定时间仍未拼成，现已无法操作']);
               }
               $thisOrder->group_id             = $thisUserGroup->id;
               $userGroupXUser                  = new UserGroupXUser();
               $userGroupXUser->user_id         = $user->id;
               $userGroupXUser->user_group_id   = $join_group_id;
               $userGroupXUser->pay_amount      = $thisGroupCourse->group_price;
               $userGroupXUser->save();
               $thisUserGroup->join_num         = $thisUserGroup->join_num + 1;
               if ($thisUserGroup->join_num >= $thisGroup->require_num){
                   $thisUserGroup->status=2;
               }
               $thisUserGroup->save();

               $thisCourse->selling_num     =$thisCourse->selling_num + 1;
               $thisCourse->save();

               $total_original_price        = $total_original_price + $thisCourse->price;
               $orderItem                   = new OrderItem();
               $orderItem->order_id         = $thisOrder->id;
               $orderItem->user_id          = $user->id;
               $orderItem->item_num         = $thisOrder->order_num.'#'.rand(1000,9999);
               $orderItem->course_id        = $thisCourse->id;
               $orderItem->original_price   = $thisCourse->price;
               $orderItem->discount_price   = $thisGroupCourse->group_price;
               $orderItem->num              = 1;
               $orderItem->total_amount     = round($orderItem->discount_price *  $orderItem->num ,2);
               $orderItem->save();
               $total_pay_amount            = $total_pay_amount + $orderItem->total_amount;
           }
           elseif($course_id) {
               //直接下单
               /** @var Course $thisCourse */
               $thisCourse=Course::whereId($course_id)->lockForUpdate()->first();
               if (!$thisCourse){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'此课程不存在']);
               }
               if ($thisCourse->status!=1){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>"课程 $thisCourse->name 暂时不可购买"]);
               }

               if($isIntegralExchange == 1){
                   $userInfo = UserInfo::whereUserId($user->id)->lockForUpdate()->first();
                   if(!$userInfo){
                       DB::rollBack();
                       return response()->json(['level' => 'error','message' => '用户信息不存在']);
                   }

                   if($thisCourse->is_integral_exchange != 1){
                       DB::rollBack();
                       return response()->json(['level' => 'error','message' => '该课程不允许使用积分兑换']);
                   }

                   if($userInfo->integral < $thisCourse->exchange_integral){
                       DB::rollBack();
                       return response()->json(['level' => 'error','message' => '用户积分不足']);
                   }

                   $userInfo->integral -= $thisCourse->exchange_integral;
                   $userInfo->save();

                   $thisCourse->selling_num += 1;
                   $thisCourse->save();

                   $orderItem                   = new OrderItem();
                   $orderItem->order_id         = $thisOrder->id;
                   $orderItem->user_id          = $user->id;
                   $orderItem->item_num         = $thisOrder->order_num.'#'.rand(1000,9999);
                   $orderItem->course_id        = $thisCourse->id;
                   $orderItem->num              = 1;
                   $orderItem->integral         = $thisCourse->exchange_integral;
                   $orderItem->total_integral   = $orderItem->integral * $orderItem->num;
                   $orderItem->save();

                   $total_pay_integral          = $total_pay_integral + $orderItem->total_integral;

                   IntegralDetail::useIntegral($user->id,$thisOrder->order_num,$total_pay_integral);
               }else{
                   if($vipType == 'num'){
                       $vipInfo = VipInfo::whereUserId($user->id)->lockForUpdate()->first();
                       if(!$vipInfo){
                           DB::rollBack();
                           return response()->json(['level' => 'error','message' => '会员信息不存在']);
                       }

                       if($vipInfo->num < $thisCourse->num_vip_price){
                           DB::rollBack();
                           return response()->json(['level' => 'error','message' => '会员次数不足']);
                       }

                       $vipInfo->num -= (int)$thisCourse->num_vip_price;
                       $vipInfo->use_num += (int)$thisCourse->num_vip_price;
                       $vipInfo->save();

                       $thisCourse->selling_num += 1;
                       $thisCourse->save();

                       $orderItem                   = new OrderItem();
                       $orderItem->order_id         = $thisOrder->id;
                       $orderItem->user_id          = $user->id;
                       $orderItem->item_num         = $thisOrder->order_num.'#'.rand(1000,9999);
                       $orderItem->course_id        = $thisCourse->id;
                       $orderItem->num              = 1;
                       $orderItem->integral         = 0;
                       $orderItem->total_integral   = 0;
                       $orderItem->total_amount     = 0;
                       $orderItem->total_vip_num    = (int)$thisCourse->num_vip_price;
                       $orderItem->save();

                       $total_vip_num = $total_vip_num + (int)$thisCourse->num_vip_price;
                   }else{
                       $thisCourse->selling_num     =$thisCourse->selling_num + 1;
                       $thisCourse->save();

                       $coursePrice = $thisCourse->show_price;
//                       if($vipType != '' && in_array($vipType,['num','time'])) {
//                           if ($vipType == 'num') {
//                               $coursePrice = $thisCourse->num_vip_price;
//                               $thisOrder->vip_type = 'num';
//                           } elseif ($vipType == 'time') {
//                               $coursePrice = $thisCourse->time_vip_price;
//                               $thisOrder->vip_type = 'time';
//                           }
//                       }
                       $vipInfo = VipInfo::whereUserId($user->id)->whereType('time')->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                        if($vipInfo && $thisCourse->time_vip_price > 0){
                            $coursePrice = $thisCourse->time_vip_price;
                        }elseif($thisCourse->price > 0){
                            $coursePrice = $thisCourse->price;
                        }

                       $orderItem                   = new OrderItem();
                       $orderItem->order_id         = $thisOrder->id;
                       $orderItem->user_id          = $user->id;
                       $orderItem->item_num         = $thisOrder->order_num.'#'.rand(1000,9999);
                       $orderItem->course_id        = $thisCourse->id;
                       $orderItem->original_price   = $thisCourse->show_price;
                       $orderItem->discount_price   = $coursePrice;
                       $orderItem->num              = 1;
                       $orderItem->total_amount     = round($orderItem->discount_price *  $orderItem->num ,2);
                       $orderItem->save();
                       $total_pay_amount            = $total_pay_amount + $orderItem->total_amount;
                       $total_original_price        = $thisCourse->show_price;
                   }
               }

           } else {
               DB::rollBack();
               return response()->json(['level'=>'error','message'=>'下单参数错误','data'=>['payload'=>$request->all()]]);
           }

           if ($coupon_id){
               //优惠券
               /** @var UserCoupon $userCoupon */
               $userCoupon = UserCoupon::whereId($coupon_id)
                   ->whereIsLocking(0)
                   ->whereIsUse(0)
                   ->whereUserId($user->id)
                   ->lockForUpdate()
                   ->first();
               if (!$userCoupon) {
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'优惠券不存在或不可用']);
               }
               if(strtotime($userCoupon->end_time) < time()){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'优惠券已过期']);
               }
               if ($total_pay_amount > 0 && $total_pay_amount < $userCoupon->satisfy_money){
                   DB::rollBack();
                   return response()->json(['level'=>'error','message'=>'实付金额未达到使用优惠券的门槛']);
               }
               $thisOrder->coupon_id            = $coupon_id;
               $thisOrder->coupon_reduce_price  = $userCoupon->money;
               $total_pay_amount                = $total_pay_amount - $userCoupon->money;
               if ($total_pay_amount <= 0 )
                   $total_pay_amount = 0;
               $userCoupon->is_locking=1;
               $userCoupon->save();

           }

           //继续处理订单
           $thisOrder->original_price   = $total_original_price;
           $thisOrder->pay_amount       = $total_pay_amount;
           $thisOrder->pay_integral     = $total_pay_integral;
           $thisOrder->pay_vip_num      = $total_vip_num;
           if($inviteUserId != 0){
               $inviteUser = User::whereId($inviteUserId)->first();
               if($inviteUser){
                   $thisOrder->invite_user_id = $inviteUserId;
               }
           }

           if ($total_pay_amount == 0 || $isIntegralExchange == 1 || $vipType=="num"){
               $thisOrder->is_pay = 1;
               $thisOrder->pay_time=date('Y-m-d H:i:s');

               if ($thisOrder->group_id){
                   $thisGroupUser=UserGroupXUser::whereUserId($thisOrder->user_id)
                       ->whereUserGroupId($thisOrder->group_id)
                       ->first();
                   if ($thisGroupUser){
                       if ($thisGroupUser->status == 0){
                           $thisGroupUser->status = 1;
                           $thisGroupUser->save();
                       }
                   }

                   $thisGroup=UserGroup::whereId($thisOrder->group_id)->first();
                   if ($thisGroup){
                       if (($thisGroup->user_id == $thisOrder->user_id) && $thisGroup->status == 0){
                           $thisGroup->status = 1;
                           $thisGroup->save();
                       }

                       if ($thisGroup->status == 1){
                           $sysGroup = SystemGroup::whereId($thisGroup->system_groups_id)->first();
                           $num = UserGroupXUser::whereUserGroupId($thisOrder->group_id)->whereStatus(1)->count();
                           if ($sysGroup){
                               if ($num >= $sysGroup->require_num){
                                   //拼团成功
                                   $thisGroup->status = 2;
                                   $thisGroup->save();
                                   $thisGroupUser = UserGroupXUser::whereUserGroupId($thisOrder->group_id)
                                       ->whereStatus(1)
                                       ->get();
                                   if (count($thisGroupUser) > 0){
                                       foreach ($thisGroupUser as $item){
                                           $item->status=2;
                                           $item->save();
                                       }
                                   }
                               }
                           }

                       }
                   }


               }

               if($thisOrder->is_pay == 1 && $thisOrder->group_id == 0){
                   $thisOrder->is_success = 1;
               }

               if($thisOrder->vip_type == 'num'){
                   $vipInfo = VipInfo::whereUserId($thisOrder->user_id)->whereType('num')->whereColumn('num','>','use_num')->first();
                   if($vipInfo){
                       $vipInfo->use_num += 1;
                       $vipInfo->save();
                   }
               }

               if(!empty($thisOrder->invite_user_id)){
                   IntegralDetail::addIntegral($thisOrder->invite_user_id,0,0,$thisOrder->id);
               }
           }
           $thisOrder->save();

           DB::commit();
        } catch (Exception $exception){
            DB::rollBack();
            return response()->json([
                'level'     =>'error',
                'message'   =>$exception->getMessage(),
                'data'      =>$exception->getTrace()
            ]);
        }

        return response()->json([
            'level'     =>$thisOrder->is_pay == 1 ?  'paying' : 'success',
            'message'   =>'下单成功',
            'data'      =>['order'=>$thisOrder,'order_item'=>OrderItem::whereOrderId($thisOrder->id)->get()]
        ]);
    }

    public function previewOrder(Request $request){

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $coupon_id          = $request->input('coupon_id',0);
        $sys_group_id       = $request->input('sys_group_id',0);
        $group_action       = $request->input('group_action','join');
        $join_group_id      = $request->input('join_group_id',0);
        $group_course_id    = $request->input('group_course_id',0);
        $packages_id        = $request->input('packages_id',0);
        $course_id_arr      = $request->input('course_id_arr',[]);
        $course_id          = $request->input('course_id',0);
        $vipType            = $request->input('vip_type','');
        $isIntegralExchange = $request->input('is_integral_exchange',0);

        if (is_string($group_action)){
            if (!in_array($group_action,['join','create']))
                return response()->json(['level'=>'error','message'=>'请选择参与拼团的方式']);
            if (!$group_course_id)
                return response()->json(['level'=>'error','message'=>'请选择参与拼团的课程']);
        }

        if($vipType != '' && in_array($vipType,['num','time'])){
            if($vipType == 'num'){
                $vipInfo = VipInfo::whereUserId($user->id)->whereType('num')->whereColumn('num','>','use_num')->first();
                if(!$vipInfo)
                    return response()->json(['level' => 'error','message' => '会员次数已用尽']);
            }elseif($vipType == 'time'){
                $vipInfo = VipInfo::whereUserId($user->id)->whereType('time')->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                if(!$vipInfo)
                    return response()->json(['level' => 'error','message' => '会员已过期']);
            }
        }

        try {
            /** 处理课程 */
            $total_show_price = 0;
            $total_original_price=0;
            $total_pay_amount    =0;
            $total_pay_num       =0;
            $coupon_reduce_price =0;
            $total_pay_integral  =0;
            $course_list         =[];
            if ($packages_id){
                //套餐下单
                $thisPackage=CoursePackage::whereId($packages_id)->first();
                if (!$thisPackage){
                    return response()->json(['level'=>'error','message'=>'套餐不存在']);
                }
                $start_time  = (int)($thisPackage->start_time ? strtotime($thisPackage->start_time) : 0);
                $end_time    = (int)($thisPackage->end_time   ? strtotime($thisPackage->end_time)   : 0);
                if ($start_time > 0 && $start_time > time()){
                    return response()->json(['level'=>'error','message'=>'套餐活动还未到开始时间']);
                }
                if ($end_time > 0 && $end_time < time()){
                    return response()->json(['level'=>'error','message'=>'套餐活动已结束']);
                }

                foreach ($course_id_arr as $course_id){
                    $thisCourse=Course::whereId($course_id)->first();
                    if (!$thisCourse){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'此课程不存在']);
                    }
                    if ($thisCourse->status!=1){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>"课程 $thisCourse->name 暂时不可购买"]);
                    }
                    /** @var CoursePackageXCourse $thisPackageCourse */
                    $thisPackageCourse=CoursePackageXCourse::whereCoursePackageId($thisPackage->id)
                        ->whereCourseId($course_id)->first();
                    if (!$thisPackageCourse){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>"套餐内无 $thisCourse->name 课程"]);
                    }
                    if ($thisPackageCourse->remain_num <= 0){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>"来晚了啦，套餐内的 $thisCourse->name 已经被其他人抢完了"]);
                    }
                    array_push($course_list,Course::getCourseInfo($course_id));

                    $total_show_price = $total_show_price + $thisCourse->show_price;
                    $total_original_price = $total_original_price + $thisCourse->price;
                    $total_pay_amount     = $total_pay_amount + $thisPackageCourse->discount_price;
                }

            } elseif ($sys_group_id && $group_action && $group_course_id){
                //拼团下单
                $thisGroup=SystemGroup::whereId($sys_group_id)->first();
                if (!$thisGroup){
//                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>'拼团活动不存在']);
                }
                $thisCourse=Course::whereId($group_course_id)->first();
                if (!$thisCourse){
//                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>'此课程不存在']);
                }
                if ($thisCourse->status!=1){
//                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>"课程 $thisCourse->name 暂时不可购买"]);
                }
                $thisGroupCourse=SystemGroupXCourse::whereSystemGroupsId($thisGroup->id)
                    ->whereCourseId($group_course_id)->first();
                if (!$thisGroupCourse){
//                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>"活动内无 $thisCourse->name 课程"]);
                }
                if ($group_action=='create'){
                    $start_time  = (int)($thisGroup->start_time ? strtotime($thisGroup->start_time) : 0);
                    $end_time    = (int)($thisGroup->end_time   ? strtotime($thisGroup->end_time)   : 0);
                    if ($start_time > 0 && $start_time > time()){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'拼团活动还未到开始时间']);
                    }
                    if ($end_time > 0 && $end_time < time()){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'拼团活动已结束']);
                    }

                } else {
                    //用户加入团
                    if ($join_group_id==0){
//                    DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'参团错误']);
                    }

                    /** @var UserGroup $thisUserGroup */
                    $thisUserGroup=UserGroup::whereId($join_group_id)->lockForUpdate()->first();
                    if (!$thisUserGroup){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'参与的团不存在']);
                    }
                    if ($thisGroup->require_num > 0 && $thisUserGroup->join_num >= $thisGroup->require_num){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'参与的团人数已满']);
                    }
                    $alreadyJoin=UserGroupXUser::whereUserId($user->id)->whereUserGroupId($join_group_id)->count();
                    if ($alreadyJoin > 0){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'不能重复参团']);
                    }
                    $exp_time=(int)strtotime($thisUserGroup->created_at) + ($thisGroup->time_limit * 3600);
                    if ($exp_time < time()){
//                        DB::rollBack();
                        return response()->json(['level'=>'error','message'=>'该团超过规定时间仍未拼成，现已无法操作']);
                    }
                }

                array_push($course_list,Course::getCourseInfo($group_course_id));
                $total_show_price            = $total_show_price + $thisCourse->show_price;
                $total_original_price        = $total_original_price + $thisCourse->price;
                $total_pay_amount            = $total_pay_amount + $thisGroupCourse->group_price;
            }
            elseif($course_id) {
                //直接下单
                $thisCourse=Course::whereId($course_id)->first();
                if (!$thisCourse){
                    return response()->json(['level'=>'error','message'=>'此课程不存在']);
                }
                if ($thisCourse->status!=1){
                    return response()->json(['level'=>'error','message'=>"课程 $thisCourse->name 暂时不可购买"]);
                }

                array_push($course_list,Course::getCourseInfo($course_id));

                if($isIntegralExchange == 1){
                    $userInfo = UserInfo::whereUserId($user->id)->first();
                    if(!$userInfo)
                        return response()->json(['level' => 'error','message' => '用户信息不存在']);

                    if($thisCourse->is_integral_exchange != 1)
                        return response()->json(['level' => 'error','message' => '该课程不允许使用积分兑换']);

                    if($userInfo->integral < $thisCourse->exchange_integral)
                        return response()->json(['level' => 'error','message' => '用户积分不足']);

                    $total_pay_integral += $thisCourse->exchange_integral;
                }else{
                    $coursePrice = $thisCourse->show_price;
//                    if($vipType != '' && in_array($vipType,['num','time'])) {
//                        if ($vipType == 'num') {
//                            $total_pay_num = round($thisCourse->num_vip_price,0);
//                        } elseif ($vipType == 'time') {
//                            $coursePrice = $thisCourse->time_vip_price;
//                        }
//                    }
                    $vipInfo = VipInfo::whereUserId($user->id)->whereType('time')->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
                    if($vipInfo && $thisCourse->time_vip_price > 0){
                        $coursePrice = $thisCourse->time_vip_price;
                    }elseif($thisCourse->price > 0){
                        $coursePrice = $thisCourse->price;
                    }

                    $total_show_price            = $total_show_price + $thisCourse->show_price;
                    $total_original_price        = $total_original_price + $thisCourse->price;
                    $total_pay_amount            = $total_pay_amount + $coursePrice;
                }
            } else {
                return response()->json(['level'=>'error','message'=>'下单参数错误','data'=>['payload'=>$request->all()]]);
            }

            if ($coupon_id){
                //优惠券
                /** @var UserCoupon $userCoupon */
                $userCoupon = UserCoupon::whereId($coupon_id)
                    ->whereIsLocking(0)
                    ->whereIsUse(0)
                    ->whereUserId($user->id)
                    ->first();
                if (!$userCoupon) {
//                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>'优惠券不存在或不可用']);
                }
                if(strtotime($userCoupon->end_time) < time()){
//                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>'优惠券已过期']);
                }
                if ($total_pay_amount > 0 && $total_pay_amount < $userCoupon->satisfy_money){
                    DB::rollBack();
                    return response()->json(['level'=>'error','message'=>'实付金额未达到使用优惠券的门槛']);
                }
                $total_pay_amount                = $total_pay_amount - $userCoupon->money;
                if ($total_pay_amount <= 0 )
                    $total_pay_amount = 0;
                $coupon_reduce_price=$userCoupon->money;
            }


        } catch (Exception $exception){
            return response()->json([
                'level'     =>'error',
                'message'   =>$exception->getMessage(),
                'data'      =>$exception->getTrace()
            ]);
        }

        return response()->json([
            'level'     =>'success',
            'message'   =>'预览成功',
            'data'      =>
                [
                    'total_show_price'      =>$total_show_price,
                    'total_pay_amount'      =>$total_pay_amount,
                    'total_pay_num'         =>$total_pay_num,
                    'total_original_price'  =>$total_original_price,
                    'coupon_reduce_price'   =>$coupon_reduce_price,
                    'total_pay_integral'    =>$total_pay_integral,
                    'course_list'           =>$course_list
                ]
        ]);
    }

    /**
     * 获取用户会员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserVipInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $vipInfoList = VipInfo::getUserVipInfo($user->id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $vipInfoList]);
    }

    /**
     * 拼团失败退款
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function handleGroupFailOrder(){
        $sysGroupList = SystemGroup::all();
        if(count($sysGroupList) > 0){
            foreach ($sysGroupList as $sysGroup) {
                if($sysGroup->time_limit){
                    $groupTime = $sysGroup->time_limit * 3600;
                }else{
                    $groupTime = 24 * 3600;
                }

                $userGroupList = UserGroup::whereSystemGroupsId($sysGroup->id)->whereStatus(1)->where('updated_at','<=',date("Y-m-d H:i:s",time() - $groupTime))->get();
                if(count($userGroupList) > 0){
                    foreach ($userGroupList as $userGroup){
                        $thisGroupUser = UserGroupXUser::whereUserGroupId($userGroup->id)->whereStatus(1)->get();
                        if (count($thisGroupUser) > 0){
                            foreach ($thisGroupUser as $item){
                                $order = Orders::whereUserId($item->user_id)->whereGroupId($userGroup->id)->first();
                                if($order){
                                    try {
                                        $refundNum = ToolsManager::makeBRefundNum();
                                        $refundResult = PaymentController::Refund($order,'拼团失败',$refundNum);
                                    } catch (\Exception $e) {
                                        Log::error('order_refund_apply_fail_info=>' . $e->getMessage());
                                    }

                                    if($refundResult && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
                                        $newActivityGroupRefund = new OrderRefund();
                                        $newActivityGroupRefund->order_id                          = $order->id;
                                        $newActivityGroupRefund->order_num                         = $order->order_num;
                                        $newActivityGroupRefund->refund_amount                     = $order->pay_amount;
                                        $newActivityGroupRefund->refund_num                        = $refundNum;
                                        $newActivityGroupRefund->save();
                                    }else{
                                        Log::notice("order_refund_fail_info=>" . isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '申请退款失败');
                                    }

                                    $item->status=3;
                                    $item->save();
                                }

                            }
                        }


                        $userGroup->status = 3;
                        $userGroup->save();
                    }
                }
            }
        }

        return 'success';
    }

    /**
     * 订单退款(没用)
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function orderRefund(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderNum = $request->input('order_num');

        $orders = Orders::whereOrderNum($orderNum)->first();
        if(!$orders)
            return response()->json(['level' => 'error','message' => '该订单不存在']);

        if($orders->is_pay != 1)
            return response()->json(['level' => 'error','message' => '订单未支付']);

        $orderRefund = OrderRefund::whereOrderId($orders->id)->whereStatus(1)->first();
        if($orderRefund)
            return response()->json(['level' => 'error','message' => '订单已退款']);

        try {
            $refundNum = ToolsManager::makeBRefundNum();
            $refundResult = PaymentController::Refund($orders,'退款',$refundNum);
        } catch (\Exception $e){
            return response()->json(['level' => 'error','message' => '退款失败，请联系客服，失败原因' . $e->getMessage()]);
        }

        if($refundResult && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
            $newActivityGroupRefund = new OrderRefund();
            $newActivityGroupRefund->order_id                          = $orders->id;
            $newActivityGroupRefund->order_num                         = $orders->order_num;
            $newActivityGroupRefund->refund_amount                     = $orders->pay_amount;
            $newActivityGroupRefund->refund_num                        = $refundNum;
            $newActivityGroupRefund->save();
        }else{
            return response()->json(['level' => 'error','message' => isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '申请退款失败']);
        }

        return response()->json(['level' => 'success','message' => '退款申请提交成功','data' => $newActivityGroupRefund]);
    }

    /**
     * 退款回调
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function refundBack(Request $request){
        $config = PaymentController::refundConfig();

        $app    = Factory::payment($config);
        $response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) {
            // 其中 $message['req_info'] 获取到的是加密信息
            // $reqInfo 为 message['req_info'] 解密后的信息

            /** @var Orders $order */
            $order = Orders::whereOrderNum($reqInfo['out_trade_no'])->first();

            $orderRefund = null;
            if($order){
                $orderRefund = OrderRefund::whereOrderId($order->id)->first();
            }

            if (!$order || ($orderRefund && $orderRefund->status == 1)) { // 如果订单不存在 或者 订单已经退过款了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if($message['return_code']=='SUCCESS'){
                $update_data = [];
                if($reqInfo['refund_status']=='SUCCESS'){
                    if($orderRefund){
                        $orderRefund->status = 1;
                        $orderRefund->save();

                        $agentOrder = AgentOrder::whereOrderNum($orderRefund->order_num)->first();
                        if($agentOrder){
                            $agentOrder->status = 2;
                            $agentOrder->save();
                        }
                    }
                }else{
                    if($orderRefund){
                        $orderRefund->status = 2;
                        $orderRefund->save();
                    }
                }

            }
            return true; // 返回 true 告诉微信“我已处理完成”
            // 或返回错误原因 $fail('参数格式校验错误');
        });

        return $response;
    }

}
